package org.easyexcel.Server;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.easyexcel.Pojo.MyReadEntry;
import org.easyexcel.Dao.JdbcBatchDao;
import org.easyexcel.Utools.ExcelConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DPF
 */
@Service
public class DataExport {
    @Autowired
    private JdbcBatchDao jdbcBatchDao;

    public void dataExport300w() {
        {
//            OutputStream outputStream = null;
            try {
                long startTime = System.currentTimeMillis();
                System.out.println("导出开始时间:" + startTime);

                // 获取响应输出流
//                outputStream = response.getOutputStream();
                // 创建ExcelWriter对象，用于写入Excel文件

                // 设置文件名，并处理中文编码问题
                String fileName = "C:\\ideaProjects\\MyEasyExcel\\src\\main\\java\\org\\easyexcel\\DoWork\\" + System.currentTimeMillis() + ".xlsx";


                // 模拟数据总量，实际应用中应根据查询条件获取
                int count = 100;
                Integer totalCount = jdbcBatchDao.findActResultLogByCondations(count);
                // 每个Sheet存放100万条数据
                Integer sheetDataRows = ExcelConstants.PER_SHEET_ROW_COUNT;
                // 每次写入20万条数据
                Integer writeDataRows = ExcelConstants.PER_WRITE_ROW_COUNT;
                // 计算需要的Sheet数量
                Integer sheetNum = totalCount % sheetDataRows == 0 ? (totalCount / sheetDataRows) : (totalCount / sheetDataRows + 1);
                // 计算每个Sheet需要写入的次数
                Integer oneSheetWriteCount = sheetDataRows / writeDataRows;
                // 计算最后一个Sheet需要写入的次数
                Integer lastSheetWriteCount = totalCount % sheetDataRows == 0 ? oneSheetWriteCount : (totalCount % sheetDataRows % writeDataRows == 0 ? (totalCount / sheetDataRows / writeDataRows) : (totalCount / sheetDataRows / writeDataRows + 1));

                // 开始分批查询并分次写入
                List<MyReadEntry> dataList = new ArrayList<>();
                for (int i = 0; i < sheetNum; i++) {
                    // 循环写入次数
                    for (int j = 0; j < (i != sheetNum - 1 ? oneSheetWriteCount : lastSheetWriteCount); j++) {
                        // 清空数据列表，便于GC清理
                        dataList.clear();
                        // 分页查询一次20w
                        PageHelper.startPage(j + 1 + oneSheetWriteCount * i, writeDataRows);
                        List<MyReadEntry> resultList = jdbcBatchDao.getAllUsers();
                        if (!CollectionUtils.isEmpty(resultList)) {
                            dataList.addAll(resultList);
                        }
                        try (ExcelWriter excelWriter = EasyExcel.write(fileName, MyReadEntry.class).build()) {
                            // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                            WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).build();
                            // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                            excelWriter.write(dataList, writeSheet);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            PageHelper.clearPage();
                            long end = System.currentTimeMillis();
                            System.out.println("导出总耗时:" + (end - startTime) / 1000 + "秒");
                        }
                    }
                }
            }finally {
                System.out.println("导出结束");
            }
        }
    }
}


//                    // 设置响应头，使浏览器下载文件
//                    response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("gb2312"), "ISO-8859-1") + ".xlsx");
//                    response.setContentType("multipart/form-data");
//                    response.setCharacterEncoding("utf-8");
//                    // 完成写入并刷新输出流
//                    EasyExcel.write().build().finish();
//                    outputStream.flush();
//                    // 导出时间结束
//                    long endTime = System.currentTimeMillis();
//                    System.out.println("导出结束时间:" + endTime + "ms");
//                    System.out.println("导出所用时间:" + (endTime - startTime) / 1000 + "秒");
//                }
//            } catch (UnsupportedEncodingException e) {
//                throw new RuntimeException(e);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            } finally {
//                if (outputStream != null) {
//                    try {
//                        outputStream.close();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }



